package com.fly.framework.shiro.realm;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.fly.framework.shiro.service.LoginService;
import com.fly.system.model.UserModel;

public class UserRealm extends AuthorizingRealm {
	
	@Autowired
	private LoginService loginService;
	
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		UsernamePasswordToken upToken = (UsernamePasswordToken) arg0;
        String username = upToken.getUsername();
		System.out.println("=====进入验证权限方法====");
		UserModel user = loginService.getUserModelByName(username);
		Set<String> role = new HashSet<String>();
		Set<String> pms = new HashSet<String>();
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 管理员拥有所有权限
        if (user.getLoginName().equals("admin")) {
            info.addRole("admin");
            info.addStringPermission("*:*:*");
        } else {
			// 角色加入AuthorizationInfo认证对象
			role.add("admin");
			info.setRoles(role);
			// 权限加入AuthorizationInfo认证对象
			pms.add("system:user:view");
			info.setStringPermissions(pms);
		}
        return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
	        System.out.println("===执行认证===");
	        UsernamePasswordToken token = (UsernamePasswordToken)arg0;

	        UserModel bean = loginService.getUserModelByName(token.getUsername());

	        if(bean == null){
	            throw new UnknownAccountException();
	        }
	        return new SimpleAuthenticationInfo(bean, bean.getPassword(),getName());
	}

}
